//
//  AdjustContentToAccommodateKeyboard.swift
//  puretennis
//
//  Created by IYE Technologies on 12/17/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class AdjustContentToAccommodateKeyboard:NSObject,UITextFieldDelegate {
    var viewController:UIViewController!;
    
    var activeTextField:UITextField!;
    
    init(target:UIViewController){
        super.init();
        self.viewController = target;
        for textField in target.view.subviews{
            if(textField is UITextField){
                (textField as UITextField).delegate = self;
            }
        }
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name: UIKeyboardWillShowNotification, object: nil);
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasHidden:"), name: UIKeyboardWillHideNotification, object: nil);
    }
    
    func keyboardWasShown(notication:NSNotification){
        var userInfo = notication.userInfo! as NSDictionary;
        var keyboardFrameAsNSValue = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey) as NSValue;
        var keyboardFrame = keyboardFrameAsNSValue.CGRectValue();
        
        if(self.activeTextField != nil){
            var textFieldFrame = self.activeTextField.frame;
            var offset = textFieldFrame.origin.y + textFieldFrame.height + 5 - (self.viewController.view.frame.size.height - keyboardFrame.size.height);
            if(offset > 0){
                UIView.beginAnimations("ResizeForKeyBoard", context: nil);
                UIView.setAnimationDuration(0.3);
                var origin = CGPoint(x: 0, y: -offset);
                self.viewController.view.frame.origin = origin;
                UIView.commitAnimations();
            }
        }
    }
    
    func keyboardWasHidden(notication:NSNotification){
        UIView.beginAnimations("ResizeForKeyBoard", context: nil);
        UIView.setAnimationDuration(0.3);
        var origin = CGPoint(x: 0, y: 0);
        self.viewController.view.frame.origin = origin;
        UIView.commitAnimations();
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        self.activeTextField = textField;
        if(textField is CustomTextField){
            var customTextField = textField as CustomTextField;
            customTextField.hidePlaceholder();
        }
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        var text = textField.text
        if(text.isEmpty && textField is CustomTextField){
            var customTextField = textField as CustomTextField;
            customTextField.showPlaceholder();
        }
    }
}
